<template>
	<view class="cloumCenter w100">
		<appBar title="添加人员"></appBar>
		<view class="cardContiner mtb20" v-for="[key, item] in Object.entries(personSetting)" :key="key">
			<view class="ps20" style="gap: 20rpx">
				<view class="titleH2 fontWeight" style="color: #000">
					{{ item.title }}
				</view>
				<form-component :ref="'formChildren' + key" :options="item.option" />
			</view>
		</view>
		<view style="width: 90%" class="mtb20">
			<ThemeButton color="linear-gradient(300deg, #fd5f47 0%, #f9773d 100%)" text="提交" @click="submit" />
		</view>
	</view>
</template>

<script>
import FormComponent from '@/components/FormComponent/FormComponent.vue'; // 引入 FormComponent
import { appSetting } from '@/common/addPersonSetting';
// 引入api方法
import { addAgencyUserApi } from '@/api/agentApi/user.js';
export default {
	components: {
		FormComponent
	},
	data() {
		return {
			personSetting: appSetting.personSetting
		};
	},
	methods: {
		// 点击提交
		submit() {
			let allFormData = {}; // 用来存放所有子组件的数据
			Object.entries(this.personSetting).forEach(([key, field]) => {
				const formChild = this.$refs['formChildren' + key];
				let childModel = formChild && formChild[0] && formChild[0].getModel();
				if (childModel) {
					allFormData[key] = childModel;
				}
			});
			let option = this.processArrays(allFormData);
			this.addAgencyUser(option);
		},
		// 参数格式处理
		processArrays(obj) {
			const list = Object.values(obj).reduce(
				(acc, curr) => ({
					...acc,
					...curr
				}),
				{}
			);
			const result = {
				...list
			};
			Object.keys(result).forEach((key) => {
				if (Array.isArray(result[key])) {
					// 如果是空数组，保持原样或设为空字符串（根据需求）
					if (result[key].length === 0) {
						result[key] = ''; // 或者保持 []，根据业务需求
					}
					// 如果是非空数组且包含url属性
					else if (result[key][0]?.url) {
						result[key] = result[key].map((item) => item.url).join(',');
					} else {
						result[key] = result[key].map((item) => item).join(',');
					}
				}
			});
			return result;
		},
		// 新增人员 TODO:校验
		async addAgencyUser(item) {
			console.log(item);
			item.wxRate = item.rateInfo.wxRate;
			item.zfbRate = item.rateInfo.zfbRate;
			item.ysfFiexdRate = item.rateInfo.ysfFiexdRate;
			item.ysfDebitRate = item.rateInfo.ysfDebitRate;
			item.ysfCappingRate = item.rateInfo.ysfCappingRate;
			item.ysfLoanRate = item.rateInfo.ysfLoanRate;
			let res = await addAgencyUserApi(item);
			if (res.code == 200) {
				uni.showToast({
					title: '添加成功'
				});
				uni.navigateBack();
			}
		}
	}
};
</script>
